package cn.edu.swu.lyt.io;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ImageDownLoader {
    private static final String LOG_FILE = "download_log.txt";
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void download(String strUrl, String targetFilePath) throws IOException {
        String fileName = new File(targetFilePath).getName();
        String status = "成功";
        String errorMsg = "";

        try {
            URL url = new URL(strUrl);
            URLConnection connection = url.openConnection();

            try (InputStream inputStream = connection.getInputStream()) {
                File outFile = new File(targetFilePath);
                File dirs = outFile.getParentFile();
                dirs.mkdirs();

                try (FileOutputStream outputStream = new FileOutputStream(targetFilePath)) {
                    int count;
                    byte[] buffer = new byte[1024 * 4];
                    while((count = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, count);
                    }
                }
            }

        } catch (IOException e) {
            status = "失败";
            errorMsg = e.getMessage();
            throw e; // 重新抛出异常保持原有逻辑
        } finally {
            // 无论成功失败都记录日志
            logDownload(fileName, strUrl, targetFilePath, status, errorMsg);
        }
    }

    /**
     * 记录下载日志
     */
    private void logDownload(String fileName, String url, String filePath, String status, String errorMsg) {
        try (FileWriter fw = new FileWriter(LOG_FILE, true);
             BufferedWriter bw = new BufferedWriter(fw);
             PrintWriter out = new PrintWriter(bw)) {

            String timestamp = DATE_FORMAT.format(new Date());
            String logEntry = String.format("[%s] 文件: %s, URL: %s, 保存路径: %s, 状态: %s%s",
                    timestamp, fileName, url, filePath, status,
                    errorMsg.isEmpty() ? "" : ", 错误: " + errorMsg);

            out.println(logEntry);
            System.out.println("下载记录: " + logEntry);

        } catch (IOException e) {
            System.err.println("写入下载日志失败: " + e.getMessage());
        }
    }

    /**
     * 查看下载历史
     */
    public static void showDownloadHistory() {
        File logFile = new File(LOG_FILE);
        if (!logFile.exists()) {
            System.out.println("暂无下载记录");
            return;
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(LOG_FILE))) {
            String line;
            System.out.println("=== 下载历史记录 ===");
            int count = 0;
            while ((line = reader.readLine()) != null) {
                System.out.println(++count + ". " + line);
            }
            if (count == 0) {
                System.out.println("暂无下载记录");
            }
        } catch (IOException e) {
            System.err.println("读取下载日志失败: " + e.getMessage());
        }
    }

    /**
     * 清空下载日志
     */
    public static void clearDownloadLog() {
        try (PrintWriter writer = new PrintWriter(LOG_FILE)) {
            writer.print("");
            System.out.println("下载日志已清空");
        } catch (IOException e) {
            System.err.println("清空下载日志失败: " + e.getMessage());
        }
    }
}